package com.dingceng.demo.base.utils

import com.dingceng.demo.base.*
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.Exception
import java.util.concurrent.TimeUnit

/**
 * 网络请求类(Retrofit+协程)
 */
object NetUtil {
    private const val PARAMS_SIGN = "_signature"
    private const val PARAMS_ACCID = "accid"
    private const val PARAMS_TOKEN = "token"
    private const val PARAMS_TIMESTAMP = "_timestamp"

    var versionName = ""

    private val mRetrofit: Retrofit by lazy {
        versionName = getVersionName(BaseApplication.getIns())
        initRetrofit()
    }

    fun getRetrofit(): Retrofit {
        return mRetrofit
    }

    private fun initRetrofit(): Retrofit {
        var builder = OkHttpClient().newBuilder()
        builder.connectTimeout(60,TimeUnit.SECONDS)
        builder.callTimeout(60,TimeUnit.SECONDS)
        builder.writeTimeout(60,TimeUnit.SECONDS)
        builder.readTimeout(60,TimeUnit.SECONDS)
        if (isDebug) {
            val loggingInterceptor = HttpLoggingInterceptor { message ->
                log(TAG, message)
            }
            loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
            builder.addNetworkInterceptor(loggingInterceptor)
        }
        builder.addInterceptor { chain ->
            try {
                val request = chain.request()
                val newRequest = request.newBuilder()
                    .addHeader("os", "android")
                    .addHeader("app-vrn", versionName)
                    .method(request.method(), request.body()).build()
                chain.proceed(newRequest)
            } catch (e: Exception) {
                log(TAG, e.toString())
                return@addInterceptor null
            }
        }
        val retrofit: Retrofit = Retrofit.Builder()
            .client(builder.build())
            .baseUrl(FORMAL_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(CoroutineCallAdapterFactory())/***************************搭配协程**********************************/
            .build()
        return retrofit
    }

    fun getTokenParams() =
        mutableMapOf(
            PARAMS_TIMESTAMP to System.currentTimeMillis().toString()
        )

    fun sign(params: Map<String, String>): String {
        val array = ArrayList<String>()
        params.forEach {
            array.add("${it.key}=${it.value}")
        }
        array.sort()
        val joinToString = "vdsns${versionName}dcyfyf" + array.joinToString("&")
        log("sign：$joinToString")
        val md5 = joinToString.md5()
//        log("md5：$md5")
        return md5
    }

    fun getSignParams(): Map<String, String> {
        val params = getTokenParams()
        val sign = sign(params)
        params[PARAMS_SIGN] = sign
        return params
    }



}
